package com.aiwhose.aiwhosewechataiwhose.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiwhose.aiwhosecore.bean.Result;
import com.aiwhose.aiwhosecore.bean.security.User;
import com.aiwhose.aiwhosewechataiwhose.utils.WeMiniAppCustomUtil;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import com.aiwhose.aiwhosewechataiwhose.service.UserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 田国刚
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    WeMiniAppCustomUtil weMiniAppCustomUtil;

    @Resource
    UserService wxUserService;

    // 查询登录状态，浏览器访问
    @GetMapping("/isLogin")
    public Result isLogin() {
        if (StpUtil.isLogin()) {
            return Result.ok();
        } else {
            return Result.ok(null,"用户未登录",401);
        }
    }

    // 注销登录
    @GetMapping("/wxlogout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok("登录状态已注销！");
    }

    // 获取微信手机号
    @GetMapping("/phoneNumber/{code}")
    public Result getPhoneNumber(@PathVariable String code) {
        String phoneNumber = weMiniAppCustomUtil.getPhoneNumber(code);
        if (StrUtil.isBlank(phoneNumber)) {
            return Result.error(phoneNumber);
        }
        String loginId = StpUtil.getLoginId().toString();
        User user = wxUserService.getById(loginId);
        user.setPhone(phoneNumber);
        wxUserService.updateById(user);
        return Result.ok(phoneNumber, "获取并绑定手机号成功");
    }

    // 微信登录
    @PostMapping("/wxlogin")
    @ResponseBody
    public Result wxLogin(@RequestBody Map<String, Object> body) {
        String code = MapUtil.get(body, "code", String.class);
        Map<String, String> map = weMiniAppCustomUtil.getOpenId(code);

        String openId = map.get("openid");
        String unionid = map.get("unionid");
        if (StrUtil.isBlank(openId)) {
            return Result.error("登陆失败");
        }
        List<User> userByWXToken = wxUserService.getUserByWXToken(openId);
        if (userByWXToken.isEmpty()) {  // 新用户，首次登录注册用户。
            User user = new User();
            user.setWxOpenId(openId);
            user.setUnionid(unionid);
            user.setSystemType("aiwhose");
            Snowflake snowflake = IdUtil.getSnowflake(1, 1);
            String userId = snowflake.nextIdStr();
            user.setId(userId);
            wxUserService.saveUser(user);
            Map<String, Object> login = login(user);
            return Result.ok(login);
        } else if (userByWXToken.size() == 1) { // 正常登录
            User user = userByWXToken.getFirst();
            if (StrUtil.isBlank(user.getUnionid()) && StrUtil.isNotBlank(unionid)) {
                user.setUnionid(unionid);
                wxUserService.updateById(user);
            }

            Map<String, Object> login = login(user);
            return Result.ok(login);
        } else { // 用户不唯一
            return Result.error("用户不唯一，请联系客服：18469138126");
        }
    }

    // 修改资料
    @PostMapping("/userUpdate")
    @ResponseBody
    public Result userUpdate(@RequestBody Map<String, Object> body) {
        User user = MapUtil.get(body, "user", User.class);
        String loginId = (String) StpUtil.getLoginId();

        if (StrUtil.isBlank(user.getNickName())) {
            user.setNickName(null);
        }
        if (StrUtil.isBlank(user.getImg())) {
            user.setImg(null);
        }

        user.setId(loginId);
        boolean b = wxUserService.updateById(user);
        return Result.ok(b);
    }

    private Map<String, Object> login(User user) {
        StpUtil.login(user.getId(), 6000);


        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        HashMap<String, Object> map = new HashMap<>();
        map.put("tokenInfo", tokenInfo);
        map.put("permissionList", new ArrayList<Object>());
        map.put("user", user);
        return map;
    }
}